import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

// 页面加载进度条
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

let flag = true
let isGetedFactory = false
router.beforeEach((to, from, next) => {

  if (to.query.factoryId && to.query.factoryId !== undefined) {
    window.localStorage.setItem('factoryId', to.query.factoryId)
  } else if (!window.localStorage.factoryId) {
    if (to.path !== '/projectList') {
      window.location.href = window.env.factoryHref
    }
  }
  if (to.query.groupId && to.query.groupId !== undefined) {
    window.localStorage.setItem('groupId', to.query.groupId)
  }

  // if (to.query.groupId && to.query.groupId !== undefined) {
  //   window.localStorage.setItem('groupId', to.query.groupId)
  // } else if (!window.localStorage.groupId) {
  //   if (to.path !== '/projectList') {
  //     window.location.href = window.env.factoryHref
  //   }
  // }

  if (!store.getters.factoryInfo.length && window.localStorage.factoryId) {
    if (!isGetedFactory) {
      isGetedFactory = true
      store.dispatch('getFactory').then(res => {})
    }
  }

  NProgress.start() // start progress bar

  if (store.getters.menus === undefined && flag === true) {
    flag = false
    store
      .dispatch("GetUserInfo")
        .then(info => {
          store.dispatch("GenerateRoutes", info.menus).then(() => {
            if (!store.getters.addRouters || store.getters.addRouters.length === 0) {
              window.location.href = window.env.factoryHref
              return
            }
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            next({ ...to
            }) // hack方法 确保addRoutes已完成
          })
        })
        .catch(e => {
          next("/")
          console.log("getInfoMenu catch and has not next")
        });
  } else {
    if (to.path == '' || to.path == '/') {
      router.push(store.getters.addRouters[0].path)
    }else if (to.matched.length === 0) {
      //如果未匹配到路由
      next("/") //如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
    } else {
      next() // hack方法 确保addRoutes已完成
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
